package com.ug.config.security;

import cn.hutool.core.util.StrUtil;
import com.ug.common.constant.CommonConstants;
import com.ug.common.enums.ErrorCode;
import com.ug.common.exception.SystemException;
import com.ug.system.entity.dto.JwtUserDto;
import com.ug.system.entity.vo.SysUserVO;
import com.ug.system.service.SysRoleService;
import com.ug.system.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Author LY
 * @create 2024/7/16 17:15
 * @Description security访问数据库UserDetailsService
 */
@RequiredArgsConstructor
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    private final SysUserService userService;

    private final SysRoleService roleService;

    private final PasswordEncoder passwordEncoder;

    /**
     * 通过用户名获取用户信息
     * @param username 登录用户名
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("security登录校验：{}", username);
        JwtUserDto jwtUserDto = null;
        SysUserVO user;
        try {
            user = userService.loadByName(username);
        } catch (SystemException e) {
            throw new UsernameNotFoundException(ErrorCode.USERNAME_OR_PASSWORD_ERROR.getMesaage(), e);
        }
        if (user == null) {
            throw new UsernameNotFoundException(ErrorCode.USERNAME_OR_PASSWORD_ERROR.getMesaage());
        }
        if (user.getEnabled() != 1) {
            throw new SystemException(ErrorCode.ACCOUNT_NOT_ACTIVATED);
        }
        if (StrUtil.equals(user.getOpenId(), username)) {
            // 使用快捷登录时，密码校验使用默认密码
            user.setPassword(passwordEncoder.encode(CommonConstants.DEFAULT_PASSWORD));
        }
        jwtUserDto = new JwtUserDto(
                user,
                roleService.getRolesByUser(user.getUserId())
        );
        return jwtUserDto;
    }
}
